from fastapi import APIRouter, Depends
from core.dependencies import get_scheduler, get_sio
from db.models.chat_message import AndroidAppMQMessage
from scheduler.msg_async_sch import MsgAsyncScheduler
from services.rabbitmq_service import RabbitMQConsumer, RabbitMQProductor
from services.wx_user_service import update_monitor_status
from utils.result import Result
router = APIRouter()
# 消费任务实例
consumers  = {}
# 消费者实例
consumer_total= {}

@router.get("/rabbitmq/refresh/{auth_key}")
async def refresh_status(auth_key: str):
    status_data = {"is_running": False}
    try:
        is_running = auth_key in consumers and not consumers[auth_key].done()
        status_data["is_running"] = is_running
        # 已经拿到当前状态，现在更新数据库中的状态
        await update_monitor_status(auth_key=auth_key, status=status_data["is_running"])
        return Result.success(data=status_data, msg="刷新成功").model_dump()
    except:
        return Result.fail(code=400, msg="刷新失败").model_dump()

@router.post("/rabbitmq/connect")
async def connect(data:dict,scheduler:MsgAsyncScheduler = Depends(get_scheduler),sio = Depends(get_sio)):
    """启动 mq 连接"""
    token_key = data.get("token_key")
    # 检查是否已经存在消费者
    if token_key in consumers and not consumers[token_key].done():
        return Result.success(msg=f"消费者 {token_key} 已经在运行").model_dump()
    # 创建新的消费者
    consumer = RabbitMQConsumer(token_key,scheduler,sio_service=sio)
    await consumer.init()
    consumer_total[token_key] =  consumer
    # 创建消费任务
    # task = asyncio.create_task(consumer.start_consuming())
    task = await consumer.start_consuming()
    consumers[token_key] = task

    return Result.success(msg=f"已启动 {token_key} 的消费者").model_dump()


@router.post("/rabbitmq/disconnect")
async def disconnect(data:dict):
    token_key = data.get("token_key")
    """停止特定 topic 的消费者"""
    try:
        if token_key in consumers:
            task = consumers[token_key]
            if not task.done():
                # 这里需要获取消费者实例来停止消费
                consumer = consumer_total[token_key]
                await consumer.stop_consuming()
            del consumers[token_key]

        return Result.success(msg=f"已停止 {token_key} 的消费者").model_dump()

    except Exception as e:
        return Result.fail(code=400, msg=f"停止消费者失败: {str(e)}").model_dump()


@router.get("/rabbitmq/status")
async def get_status(data:dict):
    """获取 MQ 连接状态"""
    token_key = data.get("token_key")

    status = token_key in consumers and not consumers[token_key].done()
    return Result.success(data=status, msg="获取状态成功").model_dump()


@router.post("/rabbitmq/product")
async def product(data:AndroidAppMQMessage):
    """测试生产者"""
    # 创建新的消费者
    product = RabbitMQProductor()
    await product.productor_message(data)
    return Result.success(msg="已经生产数据", data=data).model_dump()

@router.post("/rabbitmq/product_batch")
async def product_batch(data:list[AndroidAppMQMessage]):
    """批量测试生产者"""
    # 创建新的消费者
    product = RabbitMQProductor()
    await product.productor_message_batch(data)
    return Result.success(msg="已经生产数据", data=data).model_dump()